package com.singleton.demo07;

import java.util.HashMap;
import java.util.Map;

/**
 * 序列键生成器 采用单例模式,内部包含多个序列键信息KeyInfo对象
 */
public class KeyGenerator {
    private static KeyGenerator instance = new KeyGenerator();
    private KeyGenerator(){}
    public static KeyGenerator getInstance() {
        return instance;
    }
    private Map<String, KeyInfo> mapKeyInfo = new HashMap<>(10);
    private static final int POOL_SIZE=20;

    /**
     * TODO 有点小问题:
     * 1.效率不高,各个独立模块获取自己的序列键相互阻塞
     * 2.某个key1或者key2出现多次getNextKey得到的结果值相同
     Thread-2-------->key2------->1
     Thread-9-------->key2------->1
     Thread-3-------->key1------->1
     Thread-1-------->key1------->5
     Thread-5-------->key1------->7
     Thread-6-------->key1------->6
     Thread-4-------->key1------->4
     Thread-7-------->key2------->3
     Thread-0-------->key1------->3
     Thread-8-------->key2------->2
     Thread-10-------->key1------->2
     */
//    public synchronized int getNextKey(String keyName){
    public int getNextKey(String keyName){
        KeyInfo keyInfo;
        synchronized (keyName) {// 为何用keyName作为锁,还是出现重复的nextKey,将keyName换成this就行,或者在方法上加上synchronized,这是为何???
            //System.out.println(keyName.hashCode());
            if (mapKeyInfo.containsKey(keyName)) {
                keyInfo = mapKeyInfo.get(keyName);
            } else {
                keyInfo = new KeyInfo(keyName, POOL_SIZE);
                mapKeyInfo.put(keyName, keyInfo);
            }
            return keyInfo.getNextKey();
        }
    }

}
